package com.wngbms.feigndemo.aop;

import org.slf4j.MDC;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class ProxyRunnable implements InvocationHandler {

    private String traceId;
    private Runnable runnable;

    public ProxyRunnable(String traceId, Runnable runnable) {
        this.traceId = traceId;
        this.runnable = runnable;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            MDC.put("traceId", traceId);
            System.out.println(runnable.hashCode() + "\t" + this.hashCode());
            runnable.run();
        } finally {
            MDC.clear();
        }
        return null;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ProxyRunnable that = (ProxyRunnable) o;

        if (traceId != null ? !traceId.equals(that.traceId) : that.traceId != null) return false;
        return runnable != null ? runnable.equals(that.runnable) : that.runnable == null;
    }

    @Override
    public int hashCode() {
        int result = traceId != null ? traceId.hashCode() : 0;
        result = 31 * result + (runnable != null ? runnable.hashCode() : 0);
        return result;
    }
}

